#!/usr/local/bin/python
# Rob Dennis - Lurchington Q. Delacroix
# Keasby - TV renamer
# Project Homepage: http://code.google.com/p/keasby/

#--- Python Imports
import os
import sys
import re
import unittest
import logging
from ConfigParser import RawConfigParser

#--- Keasby Imports
from keasby_base import KeasbyError

log = logging.getLogger("keasby_logger")

class KeasbyConfigParser(RawConfigParser):
    """
    Subclass created for accepting python-formatted code from a config file,
    in a format that's desired for the application
    """

    def yield_dict_items(self):
        """
        intended as a generator for yielding all the option names
        as the keys.
        """

        for sec in self.sections():
            for opt in self.options(sec):
                yield opt, self._get_best(sec, opt)

    def _get_best(self, section, option):
        """
        Returns the value using best approximation of the type of data
        using eval
        """

        try:
            return eval(self.get(section,option),
                        # removing dangerous functions from the eval environment
                        {"__builtins__":None},

                        # adding important ones back
                        {"False":False,
                         "True":True,
                         "re":re,
                         "os":os,
                         "sys":sys,
                         "None":None})

        except Exception, error_message:
            log.warning("error parsing value: %s, %s. Using default read",
                                self.get(section,option), error_message)

            return self.get(section,option)

    def optionxform(self, optionstr):
        """
        Changes default RawConfigParser behavior to no longer enforce all lower
        case for names
        """

        return optionstr

class KeasbyConfigError(KeasbyError):
    """
    Generic KeasbyConfigError
    """

    pass

if __name__ == "__main__":
    pass